import tkinter as tk
from tkinter import messagebox, scrolledtext
from datetime import datetime
import requests
import json

# DeepSeek API配置
base_url = 'https://api.deepseek.com'
DEEPSEEK_API_KEY = "sk-d4d06b347b774b2fa4fb35a20d892eed"  # 请替换为你的DeepSeek API密钥

# 历史询问记录
history = []

# 分页相关变量
page_size = 28
current_page = 0


def get_answer(event=None):
    question = entry.get()
    if question.strip() == "请输入您要问的问题":
        messagebox.showwarning("提示", "请输入您要问的问题")
        return

    # 调用DeepSeek API获取答案
    answer = get_deepseek_answer(question)

    # 清空之前的答案
    answer_text.config(state=tk.NORMAL)
    answer_text.delete(1.0, tk.END)
    # 显示新的问题和答案
    answer_text.insert(tk.END, f"问题: {question}\n答案: {answer}\n\n")
    answer_text.config(state=tk.DISABLED)
    # 添加到历史记录
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    history.append((timestamp, question, answer))
    update_history_listbox()
    # 清空输入框并设置提示
    entry.delete(0, tk.END)
    entry.insert(0, "请输入您要问的问题")
    entry.config(fg="gray")


def get_deepseek_answer(question):
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json"
    }
    data = {
        "model": "deepseek-chat",
        "messages": [
            {
                "role": "system",
                "content": "你的名字叫做小虎得力助手,你是一个全能的助手，能够精准解答用户的问题"
            },
            {
                "role": "user",
                "content": question
            }
        ],
        "stream": True  # 启用流式传输
    }
    try:
        response = requests.post(f'{base_url}/chat/completions', headers=headers, json=data, stream=True)
        # response.raise_for_status()  # 检查请求是否成功
        # response_data = response.json()
        # return response_data.get("answer", "抱歉，我无法回答这个问题。")

        content2 = ''
        # 逐行处理流式响应
        for line in response.iter_lines():
            if line:
                decoded_line = line.decode('utf-8')
                if decoded_line.startswith("data:"):
                    try:
                        json_data = json.loads(decoded_line[5:])
                        content = json_data['choices'][0]['delta'].get('content', '')
                        if content:
                            content2+=content
                    except json.JSONDecodeError:
                        pass
        return content2
    except requests.exceptions.RequestException as e:
        return f"请求DeepSeek API时出错: {str(e)}"
    except ValueError as e:
        return f"解析DeepSeek API响应时出错: {str(e)}"


def update_history_listbox():
    global current_page
    history_listbox.delete(0, tk.END)
    start_index = current_page * page_size
    end_index = start_index + page_size
    for item in history[start_index:end_index]:
        history_listbox.insert(tk.END, f"{item[0]} - {item[1]}")
    # 更新页码显示
    update_page_label()


def show_history_answer(event):
    selected_index = history_listbox.curselection()
    if selected_index:
        index = selected_index[0] + current_page * page_size
        answer = history[index][2]
        show_answer_with_copy_button(answer)


def show_answer_with_copy_button(answer):
    # 创建一个新窗口
    answer_window = tk.Toplevel(root)
    answer_window.title("历史回复")

    # 创建一个文本框显示答案
    answer_label = tk.Label(answer_window, text=answer, wraplength=400, justify=tk.LEFT)
    answer_label.pack(pady=10)

    # 创建复制按钮
    copy_button = tk.Button(answer_window, text="复制答案", command=lambda: copy_to_clipboard(answer))
    copy_button.pack(pady=10)


def copy_to_clipboard(text):
    root.clipboard_clear()
    root.clipboard_append(text)
    messagebox.showinfo("复制成功", "答案已复制到剪贴板")


def on_entry_focus_in(event):
    if entry.get() == "请输入您要问的问题":
        entry.delete(0, tk.END)
        entry.config(fg="black")


def on_entry_focus_out(event):
    if entry.get() == "":
        entry.insert(0, "请输入您要问的问题")
        entry.config(fg="gray")


def on_closing():
    if messagebox.askokcancel("退出", "你确定要退出吗？"):
        root.destroy()


def copy_answer():
    answer = answer_text.get(1.0, tk.END).strip()
    root.clipboard_clear()
    root.clipboard_append(answer)
    messagebox.showinfo("复制成功", "答案已复制到剪贴板")


def next_page():
    global current_page
    if (current_page + 1) * page_size < len(history):
        current_page += 1
        update_history_listbox()


def prev_page():
    global current_page
    if current_page > 0:
        current_page -= 1
        update_history_listbox()


def update_page_label():
    total_pages = (len(history) + page_size - 1) // page_size
    page_label.config(text=f"第 {current_page + 1} 页，共 {total_pages} 页")


# 创建主窗口
root = tk.Tk()
root.title("小虎语言大模型V1.0")
root.geometry("1000x700")  # 设置窗口大小

# 创建左侧的历史记录框架
history_frame = tk.Frame(root, width=250)
history_frame.pack(side=tk.LEFT, fill=tk.Y)

# 创建历史记录标签
history_label = tk.Label(history_frame, text="历史询问记录：")
history_label.pack(pady=10)

# 创建红色字体提示
hint_label = tk.Label(history_frame, text="双击查看历史回复", fg="red")
hint_label.pack(pady=5)

# 创建历史记录列表框
history_listbox = tk.Listbox(history_frame, height=30, width=30)
history_listbox.pack(pady=10, fill=tk.BOTH, expand=True)
history_listbox.bind('<Double-Button-1>', show_history_answer)

# 创建分页按钮和页码标签
page_frame = tk.Frame(history_frame)
page_frame.pack(pady=10)

prev_button = tk.Button(page_frame, text="上一页", command=prev_page)
prev_button.pack(side=tk.LEFT, padx=10)

next_button = tk.Button(page_frame, text="下一页", command=next_page)
next_button.pack(side=tk.RIGHT, padx=10)

page_label = tk.Label(page_frame, text="第 1 页，共 1 页")
page_label.pack(side=tk.BOTTOM, pady=10)

# 创建右侧的问答框框架
qa_frame = tk.Frame(root)
qa_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

# 创建退出按钮
exit_button = tk.Button(qa_frame, text="退出", command=on_closing)
exit_button.pack(side=tk.TOP, anchor=tk.NE, padx=10, pady=10)

# 创建标签
label = tk.Label(qa_frame, text="请输入你的问题：")
label.pack(pady=10)

# 创建输入框并设置提示
entry = tk.Entry(qa_frame, width=100)
entry.insert(0, "请输入您要问的问题")
entry.config(fg="gray")
entry.pack(pady=10)
entry.bind('<FocusIn>', on_entry_focus_in)
entry.bind('<FocusOut>', on_entry_focus_out)
entry.bind('<Return>', get_answer)

# 创建按钮
button = tk.Button(qa_frame, text="获取答案", command=get_answer)
button.pack(pady=10)

# 创建用于显示答案的文本框
answer_text = scrolledtext.ScrolledText(qa_frame, height=20, width=100)
answer_text.pack(pady=10)
answer_text.config(state=tk.DISABLED)  # 禁用答案框的编辑功能

# 创建复制按钮
copy_button = tk.Button(qa_frame, text="复制答案", command=copy_answer)
copy_button.pack(pady=10)

# 绑定关闭窗口事件
root.protocol("WM_DELETE_WINDOW", on_closing)

# 运行主循环
root.mainloop()